﻿using System;

namespace UniRx.Operators
{
	// Token: 0x02000279 RID: 633
	internal class ContinueWithObservable<TSource, TResult> : OperatorObservableBase<TResult>
	{
		// Token: 0x06000E48 RID: 3656 RVA: 0x000436FC File Offset: 0x00041AFC
		public ContinueWithObservable(IObservable<TSource> source, Func<TSource, IObservable<TResult>> selector) : base(source.IsRequiredSubscribeOnCurrentThread<TSource>())
		{
			this.source = source;
			this.selector = selector;
		}

		// Token: 0x06000E49 RID: 3657 RVA: 0x00043718 File Offset: 0x00041B18
		protected override IDisposable SubscribeCore(IObserver<TResult> observer, IDisposable cancel)
		{
			return new ContinueWithObservable<TSource, TResult>.ContinueWith(this, observer, cancel).Run();
		}

		// Token: 0x04000843 RID: 2115
		private readonly IObservable<TSource> source;

		// Token: 0x04000844 RID: 2116
		private readonly Func<TSource, IObservable<TResult>> selector;

		// Token: 0x0200027A RID: 634
		private class ContinueWith : OperatorObserverBase<TSource, TResult>
		{
			// Token: 0x06000E4A RID: 3658 RVA: 0x00043727 File Offset: 0x00041B27
			public ContinueWith(ContinueWithObservable<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel)
			{
				this.parent = parent;
			}

			// Token: 0x06000E4B RID: 3659 RVA: 0x00043744 File Offset: 0x00041B44
			public IDisposable Run()
			{
				SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable();
				this.serialDisposable.Disposable = singleAssignmentDisposable;
				singleAssignmentDisposable.Disposable = this.parent.source.Subscribe(this);
				return this.serialDisposable;
			}

			// Token: 0x06000E4C RID: 3660 RVA: 0x00043780 File Offset: 0x00041B80
			public override void OnNext(TSource value)
			{
				this.seenValue = true;
				this.lastValue = value;
			}

			// Token: 0x06000E4D RID: 3661 RVA: 0x00043790 File Offset: 0x00041B90
			public override void OnError(Exception error)
			{
				try
				{
					this.observer.OnError(error);
				}
				finally
				{
					base.Dispose();
				}
			}

			// Token: 0x06000E4E RID: 3662 RVA: 0x000437C8 File Offset: 0x00041BC8
			public override void OnCompleted()
			{
				if (this.seenValue)
				{
					IObservable<TResult> observable = this.parent.selector(this.lastValue);
					this.serialDisposable.Disposable = observable.Subscribe(this.observer);
				}
				else
				{
					try
					{
						this.observer.OnCompleted();
					}
					finally
					{
						base.Dispose();
					}
				}
			}

			// Token: 0x04000845 RID: 2117
			private readonly ContinueWithObservable<TSource, TResult> parent;

			// Token: 0x04000846 RID: 2118
			private readonly SerialDisposable serialDisposable = new SerialDisposable();

			// Token: 0x04000847 RID: 2119
			private bool seenValue;

			// Token: 0x04000848 RID: 2120
			private TSource lastValue;
		}
	}
}
